<template>
    <PanelHead :route="route" />
    <div class="btn">
        <el-button :icon="Plus" type="primary" size="small" @click="open(null)">
            新增
        </el-button>
    </div>
    <el-table :data="tableData.list" style="width: 100%">
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="permissionName" label="菜单权限" width="500px" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-info">
        <el-pagination v-model:current-page="paginationData.pageNum" :page-size="paginationData.pageSize"
            :background="false" layout="total, prev, pager, next" :total="tableData.total" size="small"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="添加权限" width="500px">
        <el-form ref="formRef" label-width="100px" label-position="left" :model="form" :rules="rules">
            <el-form-item prop="id" v-show="false">
                <el-input v-model="form.id" />
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入权限名称" />
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
                <el-tree style="max-width: 600px" :data="permissionData" node-key="id" show-checkbox
                    :default-checked-keys="defaultkeys" ref="treeRef" :default-expanded-keys="[2]" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button type="primary" @click="confirm(formRef)">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { userGetMenu, userSetMenu, menuList } from '../../../api';
import type { FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router'

// 获取pinia数据
const route = useRoute();

interface formType {
    id: number,
    name: string,
    permission: number[],
    permissionName: string
}
onMounted(() => {
    userGetMenu().then(({ data }) => {
        permissionData.value = data.data;
    });
    getListData()
});
const paginationData = reactive({
    pageNum: 1,
    pageSize: 10
});
// 请求列表数据
// 列表数据
const tableData = ref({
    list: [],
    total: 0
});
const handleSizeChange = (val: number) => {
    paginationData.pageSize = val;
    getListData()
}
const handleCurrentChange = (val: number) => {
    paginationData.pageNum = val;
    getListData()
}
const getListData = () => {
    menuList(paginationData).then(({ data }) => {
        // 处理响应数据
        const { list, total } = data.data
        tableData.value = { list, total }
    });
}
// 弹窗的显示隐藏
const dialogFormVisible = ref(false);
// 表单数据
const form: formType = reactive({
    name: '',
    permission: [],
    id: 0,
    permissionName: ''
});
// 权限树型结构菜单数据
const permissionData = ref([]);

// 关闭弹窗的回调
const beforeClose = () => {
    dialogFormVisible.value = false;
    // 重置表单
    formRef.value?.resetFields()
    // tree选择重置
    treeRef.value.setCheckedKeys(defaultkeys)
}
// 打开弹窗
const open = (rowData: formType | null) => {
    dialogFormVisible.value = true;
    // 弹窗打开form生成是异步的 因此使用nextTick 
    nextTick(() => {
        if (rowData) {
            Object.assign(form, { id: rowData.id, name: rowData.name });
            treeRef.value.setCheckedKeys(rowData.permission);
        }
    });
}
// 选中权限
const defaultkeys = [4, 5]
// 组件数据
const treeRef = ref()

// 表单提交 表单校验是异步
// 表单校验数据
const formRef = ref<FormInstance>()
// 表单校验 trigger:失去焦点的时候 
const rules = reactive({
    name: [{ required: true, trigger: 'blur', message: '请输入权限名称' }],
})
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 手动触发表单校验
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 获取到选择的checkbox数据
            const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
            // 提交表单
            userSetMenu({ name: form.name, permissions, id: form.id }).then(({ data }) => {
                beforeClose()
                getListData()
            })
        } else {
            // 处理表单校验失败
            console.log('error submit!', fields)
        }
    })
}
</script>

<style scoped lang="less">
    .btn{
        padding: 10px 0 10px 10px;
        background-color: #fff;
    }
</style>